package com.qianniu.napi.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.List;

/**
 * Created by chenxuebin on 16/9/12.
 */
public class HttpUtils {

    private final static Logger logger = LoggerFactory.getLogger(HttpUtils.class);

    /**
     * 向指定ulr发起post请求，并返回请求结果
     *
     * @param url
     * @param formParams
     * @return
     */
    public static String httpPost(String url, List<NameValuePair> formParams) {
        String json = "";
        HttpPost httpPost = new HttpPost(url); // 目标地址URL
        HttpClient httpclient = HttpClients.createDefault();
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(formParams, "utf-8"));
            HttpResponse response = httpclient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                logger.error("getMsgFromHttpPost failed,url:" + url + ",http StatusCode:" + response.getStatusLine().getStatusCode() + ",post parameter:[" + JSON.toJSONString(formParams) + "]");
            } else {
                json = EntityUtils.toString(entity);
                EntityUtils.consume(entity);
            }
        } catch (UnsupportedEncodingException e) {
            logger.error("get msg from http post fail:", e);
        } catch (IOException e) {
            logger.error("get msg from http post err:", e);
        } finally {
            httpPost.releaseConnection();
            httpclient = null;
            httpPost = null;
        }
        return json;
    }

    /**
     * 向指定ulr发起post请求，并返回请求结果
     *
     * @param url
     * @param content
     * @return
     */
    public static String httpPost(String url, String content) {
        String json = "";
        HttpPost httpPost = new HttpPost(url); // 目标地址URL
        HttpClient httpclient = HttpClients.createDefault();
        try {
            httpPost.setHeader("Content-Type", "text/plain; charset=UTF-8");
            httpPost.setEntity(new StringEntity(content, "UTF-8"));
            HttpResponse response = httpclient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                logger.error("getMsgFromHttpPost failed,url:" + url + ",http StatusCode:" + response.getStatusLine().getStatusCode());
            } else {
                json = EntityUtils.toString(entity);
                EntityUtils.consume(entity);
            }
        } catch (UnsupportedEncodingException e) {
            logger.error("get msg from http post fail:", e);
        } catch (IOException e) {
            logger.error("get msg from http post err:", e);
        } finally {
            httpPost.releaseConnection();
            httpclient = null;
            httpPost = null;
        }
        return json;
    }

    public static String postFile(String url, String key, String filePath) {

        logger.debug(">>>>>> start to postFile at url = " + url);
        String json = "";
        HttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        try {
            FileBody fileBody = new FileBody(new File(filePath));

            MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
            entityBuilder.addPart(key, fileBody);
//            entityBuilder.setCharset(Charset.defaultCharset());
//            entity.addBinaryBody("media", new File(filePath));

            httpPost.setEntity(entityBuilder.build());
            HttpResponse response = httpclient.execute(httpPost);

            HttpEntity entity = response.getEntity();
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                logger.error("postFile failed,url:" + url + ",http StatusCode:" + response.getStatusLine().getStatusCode());
            } else {
                json = EntityUtils.toString(entity);
                EntityUtils.consume(entity);
            }
        } catch (UnsupportedEncodingException e) {
            logger.error("get msg from http post fail:", e);
        } catch (IOException e) {
            logger.error("get msg from http post err:", e);
        } finally {
            httpPost.releaseConnection();
            httpclient = null;
            httpPost = null;
        }
        return json;
    }


    public static String postFile(String url, String key, String filePath,
                                  String paramKey, String paramValue) {

        logger.debug(">>>>>> start to postFile at url = " + url);
        String json = "";
        HttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        try {
            FileBody fileBody = new FileBody(new File(filePath));

            MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
            entityBuilder.addPart(key, fileBody);
            if (!Strings.isNullOrEmpty(paramKey)) {
                logger.debug(">>>addPart");
//                entityBuilder.addTextBody(paramKey, paramValue);
                StringBody stringBody = new StringBody(paramValue, ContentType.APPLICATION_JSON);
                entityBuilder.addPart(paramKey, stringBody);
            }
//            entityBuilder.setCharset(Charset.defaultCharset());
//            entity.addBinaryBody("media", new File(filePath));

            httpPost.setEntity(entityBuilder.build());
            HttpResponse response = httpclient.execute(httpPost);

            HttpEntity entity = response.getEntity();
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                logger.error("postFile failed,url:" + url + ",http StatusCode:" + response.getStatusLine().getStatusCode());
            } else {
                json = EntityUtils.toString(entity);
                EntityUtils.consume(entity);
            }
        } catch (UnsupportedEncodingException e) {
            logger.error("get msg from http post fail:", e);
        } catch (IOException e) {
            logger.error("get msg from http post err:", e);
        } finally {
            httpPost.releaseConnection();
            httpclient = null;
            httpPost = null;
        }
        return json;
    }

    /**
     * 获取指定url资源
     *
     * @param url
     * @return
     */
    public static String httpGet(String url) {
        HttpClient httpclient = HttpClients.createDefault();

        HttpGet httpget = new HttpGet(url);
        StringBuilder sb = new StringBuilder();
        // logger.debug("--------------------------------------==start print get url==========================");
        // logger.debug(url);
        try {
            HttpResponse response = httpclient.execute(httpget);
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                String content = "httpGet failed,url:" + url + ",http StatusCode:" + response.getStatusLine().getStatusCode();
                logger.error(content);
            } else {
                BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "utf-8"));
                String lineStr;
                while ((lineStr = reader.readLine()) != null) {
                    sb.append(lineStr);
                }
                reader.close();
            }
        } catch (Exception e) {
            logger.error("======error", e);
        } finally {
            httpget.releaseConnection();
        }
        String result = sb.toString();
        logger.debug("result from http get:" + result);
        return result;
    }

    public static void downloadFile(String imaurl, String targetFile) {
        // 下载网络文件
        int bytesum = 0;
        int byteread = 0;

        try {
            logger.debug(">>>>>> downloadFile start and imaurl=" + imaurl);
            URL url = new URL(imaurl);
            File file = new File(targetFile);
            if (file.exists()) {
                file.delete();
                file = new File(targetFile);
//                return;
            }

//            try {
//                Thread.sleep(500);
//            }catch (Exception e){
//                logger.error("thread.sleep interupt",e);
//            }

            checkDirectory(targetFile);

            URLConnection conn = url.openConnection();
            InputStream inStream = conn.getInputStream();
            FileOutputStream fs = new FileOutputStream(targetFile);

            byte[] buffer = new byte[1204];
            while ((byteread = inStream.read(buffer)) != -1) {
                bytesum += byteread;
                fs.write(buffer, 0, byteread);
            }
            logger.debug(">>>>>> downloadFile OK and targetFile=" + targetFile);
        } catch (FileNotFoundException e) {
            logger.error("FileNotFoundException", e);
        } catch (IOException e) {
            logger.error("IOException", e);
        }
    }

    // 检查路径的所有目录是否创建
    public static void checkDirectory(String path) {

        if (Strings.isNullOrEmpty(path)) return;
        if (path.indexOf("img") <= 0) return;
        int uploadsIndex = path.indexOf("img");

        String headpath = path.substring(0, uploadsIndex);
        String leftpath = path.substring(uploadsIndex);
        String[] arr = leftpath.split("/");

        String targetpath = headpath;
        for (int i = 0; i < arr.length - 1; i++) {
            targetpath = targetpath + arr[i] + "/";
            createDir(targetpath);
        }
    }

    // 创建目录
    public static boolean createDir(String destDirName) {
        File dir = new File(destDirName);
        if (dir.exists()) {// 判断目录是否存在
            return false;
        }
        if (!destDirName.endsWith(File.separator)) {// 结尾是否以"/"结束
            destDirName = destDirName + File.separator;
        }
        if (dir.mkdirs()) {// 创建目标目录
            return true;
        } else {
            return false;
        }
    }

    public static void main(String args[]) throws IOException {

        //向文件中写数据

        FileChannel fc = new FileOutputStream("/Users/chenxuebin/imgs/test.txt").getChannel();

        fc.write(ByteBuffer.wrap("你好，".getBytes()));

        fc.close();

    }

    public static String post(String url, com.alibaba.fastjson.JSONObject json) {

        HttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);

        post.setHeader("Content-Type", "application/json");
//        post.addHeader("Authorization", "Basic YWRtaW46");
        String result = "";

        try {

            StringEntity s = new StringEntity(json.toString(), "utf-8");
//            httpPost.setHeader("Content-Type","text/plain; charset=UTF-8");

            s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            post.setEntity(s);

            // 发送请求
            HttpResponse httpResponse = client.execute(post);

            // 获取响应输入流
            InputStream inStream = httpResponse.getEntity().getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    inStream, "utf-8"));
            StringBuilder strber = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null)
                strber.append(line + "\n");
            inStream.close();

            result = strber.toString();
            System.out.println(result);
            logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> result=" + result);
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                System.out.println("请求服务器成功，做相应处理");
            } else {
                System.out.println("请求服务端失败");
            }
        } catch (Exception e) {
            logger.error(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> post method error",e);
            throw new RuntimeException(e);
        } finally {
            //client.
        }
        return result;
    }

}
